//
//  OnlineProductsViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-6-4.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "OnlineProductsViewController.h"
#import "JSON.h"
#import "NYProduct.h"
#import "OnlineProductTableCell.h"
#import "NYMemberCenterDataManager.h"
#import "ProductDetailViewController.h"
#import "MenuDataManager.h"
#import "NYProductAd.h"

#define kOnlineProductDownloaderKey     @"OnlineProductDownloaderKey"
#define kOnlineProductAdDownloaderKey   @"OnlineProductAdDownloaderKey"

static NSInteger kNumOfPage = 10;
static NSInteger kInitPageNum = 1;
static NSInteger kCurrentPageNum = 1;

@interface OnlineProductsViewController ()

@end

@implementation OnlineProductsViewController

@synthesize onlineProsTableView,moreView;
@synthesize products,productAds;
@synthesize productTypeId;
@synthesize imagesContainView;
@synthesize menuName;
@synthesize placeHolderImageView;
@synthesize productAdsResponsed,productsResponsed;

- (MoreView *)moreView
{
    if(nil == moreView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"MoreView" owner:self options:nil];
        moreView = [[nibs lastObject] retain];
        moreView.delegate = self;
    }
    return moreView;
}

- (ImagesContainView *)imagesContainView
{
    if(nil == imagesContainView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"ImagesContainView" owner:self options:nil];
        imagesContainView = [[nibs lastObject] retain];
        imagesContainView.bgLabelImageView.hidden = NO;
        imagesContainView.nameLabel.hidden = NO;
        imagesContainView.delegate = self;
    }
    return imagesContainView;
}
#pragma mark - Public methods
- (void)callServerToGetOnlineProductsList:(NSString *)accountId
                            typeCoustomer:(NSString *)typeCustomer
                               orderByCnd:(NSString *)orderByCnd
                                   pageNo:(NSString *)pageNo
                                 pageSize:(NSString *)pageSize
                               updateTime:(NSString *)updateTime
{
    NSString *suburl = [NSString stringWithFormat:kOnlineProduectsUrl,@"jsonp",accountId,typeCustomer,orderByCnd,pageNo,pageSize,updateTime];
    if([self.menuName isEqualToString:@"固定收益"])
    {
        suburl = [suburl stringByAppendingString:@"app000051"];
    }
    else if([self.menuName isEqualToString:@"浮动收益"])
    {
        suburl = [suburl stringByAppendingString:@"app000052"];
    }
    else if([self.menuName isEqualToString:@"现金管理"])
    {
        suburl = [suburl stringByAppendingString:@"app000053"];
    }
    else
    {
        suburl = [suburl stringByAppendingString:@"app000050"];
    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kOnlineProductDownloaderKey];
}

- (void)callServerToGetOnlineProducts
{
    NSString *accountId = nil;
    if(nil == [NYMemberCenterDataManager sharedManager].loginMember.accountId)
        accountId = @"";
    else
        accountId = [NYMemberCenterDataManager sharedManager].loginMember.accountId;
    [self callServerToGetOnlineProductsList:accountId typeCoustomer:self.productTypeId orderByCnd:@"1" pageNo:[NSString stringWithFormat:@"%d",kCurrentPageNum] pageSize:[NSString stringWithFormat:@"%d",kNumOfPage] updateTime:@""];
}

- (void)refreshProductsList
{
    kCurrentPageNum = kInitPageNum;
    [self callServerToGetOnlineProducts];
}

- (void)refreshProductsAds
{
    NSString *suburl = [NSString stringWithFormat:kOnlineProductAdUrl,@"jsonp",self.productTypeId,@""];
    suburl = [suburl stringByAppendingString:@"app000055"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kOnlineProductAdDownloaderKey];
}

- (void)refreshAllData
{
    self.productsResponsed = NO;
    self.productAdsResponsed = NO;
    [self refreshProductsAds];
    [self refreshProductsList];
}

- (void)stopRefreshData
{
    if(self.productAdsResponsed && self.productsResponsed)
    {
        //两个请求全部返回
        [self.onlineProsTableView doneLoadingTableViewData];
        if(self.productAds.count == 0 && self.products.count == 0)
        {
            self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
            self.placeHolderImageView.hidden = NO;
            self.onlineProsTableView.hidden = YES;
        }
        else
        {
            self.onlineProsTableView.hidden = NO;
            self.placeHolderImageView.hidden = YES;
        }
    }
}

#pragma mark - Notification methods
- (void)refreshOnlineProductsWithNotification:(NSNotification *)notification
{
    [self refreshAllData];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle:self.menuName];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshOnlineProductsWithNotification:) name:kRefreshOnlneProductsNotification object:nil];
    self.products = [NSMutableArray array];
    self.productAds = [NSMutableArray array];
    self.onlineProsTableView.refreshTableView.backgroundColor = [UIColor clearColor];
    [self.onlineProsTableView startManualLoading];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        self.view = nil;
        self.onlineProsTableView = nil;
        self.moreView = nil;
        self.imagesContainView = nil;
        self.placeHolderImageView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.onlineProsTableView = nil;
    self.moreView = nil;
    self.imagesContainView = nil;
    self.placeHolderImageView = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [placeHolderImageView release];
    [imagesContainView release];
    [menuName release];
    [productTypeId release];
    [moreView release];
    [products release];
    [productAds release];
    [onlineProsTableView release];
    [super dealloc];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    OnlineProductTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"OnlineProductTableCell" owner:self options:nil];
        cell = [nibs lastObject];
        UIImageView *bgView = [[UIImageView alloc] initWithFrame:cell.bounds];
        bgView.image = [UIImage imageNamed:@"bg_selection@2x.png"];
        cell.selectedBackgroundView = bgView;
        [bgView release];
    }
    NYProduct *nyp = [self.products objectAtIndex:indexPath.row];
    
    CGRect rect = cell.textContainView.frame;
    
    NSString *imagePath = nyp.img_url;
    if(imagePath)
        imagePath = [imagePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if(imagePath && ![imagePath isEqualToString:@""])
    {
        rect.size.width = 240.f;
        cell.iconImageView.hidden = NO;
        [cell.iconImageView aysnLoadImageWithUrl:imagePath placeHolder:@"loading_icon@2x.png"];
    }
    else
    {
        rect.size.width = tableView.frame.size.width-10.f;
        cell.iconImageView.hidden = YES;
    }
    cell.textContainView.frame = rect;
    cell.mingchengLabel.text = nyp.public_product_name;
    
    //设置状态label 的元素状态
    NYElement *nye = nil;
    for(NYElement *element in [MenuDataManager sharedManager].elements)
    {
        if([element.elementId isEqualToString:kOnlineProductStatusLabelId])
        {
            nye = element;
            break;
        }
    }
    cell.statusLabel.text = nyp.status;
    if(nye.elementAccess == kElementInvisiable)
    {
        cell.statusLabel.hidden = YES;
    }
    else
    {
        cell.statusLabel.hidden = NO;
    }
    cell.liangdianLabel.text = nyp.product_feature;
    cell.shouyilvLabel.text = nyp.product_yield;
    cell.nianxianLabel.text = nyp.product_term;
    if([nyp.isbooking isEqualToString:@"1"])
    {
        cell.markImageView.hidden = NO;
    }
    else
    {
        cell.markImageView.hidden = YES;
    }
    return cell;
}

#pragma mark - RYPullDownRefreshTableViewDelegate methods
- (void)didTriggerPullDownRefresh
{
    [self refreshAllData];
}

#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([[NYMemberCenterDataManager sharedManager] isLogin])
    {
        NYProduct *nyp = [self.products objectAtIndex:indexPath.row];
        ProductDetailViewController *pdvc = [[ProductDetailViewController alloc] init];
        pdvc.isForCollect = NO;
        pdvc.product = nyp;
        [self.navigationController pushViewController:pdvc animated:YES];
        [pdvc release];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowLoginViewNotification object:nil];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kOnlineProductTableCellHeight;
}

#pragma mark - MoreViewDelegate method
- (void)didMoreViewClicked
{
    ++kCurrentPageNum;
    [self callServerToGetOnlineProducts];
}

#pragma mark - ImagesContainViewDelegate method
- (void)didTappedWithProductAd:(NYProductAd *)productAd
{
    if([[NYMemberCenterDataManager sharedManager] isLogin])
    {
        if([productAd.productbooking_id isEqualToString:@""] || nil == productAd.productbooking_id)
            return;
        NYProduct *nyp = [[NYProduct alloc] init];
        nyp.productbooking_id = productAd.productbooking_id;
        nyp.public_product_name = productAd.public_product_name;
        ProductDetailViewController *pdvc = [[ProductDetailViewController alloc] init];
        pdvc.product = nyp;
        [nyp release];
        [self.navigationController pushViewController:pdvc animated:YES];
        [pdvc release];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowLoginViewNotification object:nil];
    }
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    
    if([downloader.purpose isEqualToString:kOnlineProductDownloaderKey])
    {
        self.productsResponsed = YES;
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            if(kCurrentPageNum == kInitPageNum)
                self.products = [NSMutableArray array];
            NSArray *array = [dict objectForKey:@"list"];
            for(NSDictionary *dict in array)
            {
                NYProduct *nyp = [[NYProduct alloc] init];
                for(NSString *key in [dict allKeys])
                {
                    @try {
                        [nyp setValue:[dict objectForKey:key] forKey:key];
                    }
                    @catch (NSException *exception) {
                        NSLog(@"试图添加不存在的key: %@到NYProduct实例中.",key);
                    }
                }
                [self.products addObject:nyp];
                [nyp release];
            }
            
            if(array.count == kNumOfPage)
                self.onlineProsTableView.refreshTableView.tableFooterView = self.moreView;
            else
                self.onlineProsTableView.refreshTableView.tableFooterView = nil;
            
            //重新加载产品列表
            [self.onlineProsTableView.refreshTableView reloadData];
        }
        else
        {
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
            self.onlineProsTableView.refreshTableView.tableFooterView = nil;
        }
    }
    else
    {
        self.productAdsResponsed = YES;
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            NSMutableArray *productAdsArray = [NSMutableArray array];
            NSArray *adArray = [dict objectForKey:@"list"];
            for(NSDictionary *dictAd in adArray)
            {
                NYProductAd *productAd = [[NYProductAd alloc] init];
                productAd.image_url = [dictAd objectForKey:@"image_url"];
                productAd.remark = [dictAd objectForKey:@"remark"];
                productAd.productbooking_id = [dictAd objectForKey:@"productbooking_id"];
                productAd.public_product_name = [dictAd objectForKey:@"public_product_name"];
                [productAdsArray addObject:productAd];
                [productAd release];
            }
            self.productAds = productAdsArray;
            if(adArray.count > 0)
            {
                [self.imagesContainView reloadWithProductAds:productAdsArray];
                self.onlineProsTableView.refreshTableView.tableHeaderView = self.imagesContainView;
            }
            else
            {
                self.onlineProsTableView.refreshTableView.tableHeaderView = nil;
            }
        }
        else
        {
            self.onlineProsTableView.refreshTableView.tableHeaderView = nil;
        }
    }
    [self stopRefreshData];
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if([downloader.purpose isEqualToString:kOnlineProductDownloaderKey])
    {
        self.productsResponsed = YES;
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
    }
    else
    {
        self.productAdsResponsed = YES;
    }
    [self stopRefreshData];
}
@end
